"""
The driver is based on devbis' st7789py_mpy module from
https://github.com/devbis/st7789py_mpy.

This driver adds support for:

- 320x240, 240x240 and 135x240 pixel displays
- Display rotation
- Hardware based scrolling
- Drawing text using 8 and 16 bit wide bitmap fonts with heights that are
  multiples of 8.  Included are 12 bitmap fonts derived from classic pc
  BIOS text mode fonts.
- Drawing text using converted TrueType fonts.
- Drawing converted bitmaps

"""

'''
导入字体
'''
from tft import font_gb_16x16 as font_gb
from tft import vga1_16x32 as font16
from tft import vga1_8x16 as font8

from tft import GBfont
import time
from micropython import const
import ustruct as struct

GB16 = GBfont.gb2312(16)  # UNICODE字体
GB24 = GBfont.gb2312(24)  # UNICODE字体
GB32 = GBfont.gb2312(32)  # UNICODE字体
# GB32 = font_gb.Font32(32)  # 自定义图形字体
GB48 = font_gb.Font48(48)  # 自定义图形字体
# commands
ST7789_NOP = const(0x00)
ST7789_SWRESET = const(0x01)
ST7789_RDDID = const(0x04)
ST7789_RDDST = const(0x09)

ST7789_SLPIN = const(0x10)
ST7789_SLPOUT = const(0x11)
ST7789_PTLON = const(0x12)
ST7789_NORON = const(0x13)

ST7789_INVOFF = const(0x20)
ST7789_INVON = const(0x21)
ST7789_DISPOFF = const(0x28)
ST7789_DISPON = const(0x29)
ST7789_CASET = const(0x2A)
ST7789_RASET = const(0x2B)
ST7789_RAMWR = const(0x2C)
ST7789_RAMRD = const(0x2E)

ST7789_PTLAR = const(0x30)
ST7789_VSCRDEF = const(0x33)
ST7789_COLMOD = const(0x3A)
ST7789_MADCTL = const(0x36)
ST7789_VSCSAD = const(0x37)

ST7789_MADCTL_MY = const(0x80)  # D7
ST7789_MADCTL_MX = const(0x40)  # D6
ST7789_MADCTL_MV = const(0x20)  # D5
ST7789_MADCTL_ML = const(0x10)  # D4
ST7789_MADCTL_BGR = const(0x08)  # D3
ST7789_MADCTL_MH = const(0x04)  # D2
ST7789_MADCTL_RGB = const(0x00)  # D0

ST7789_RDID1 = const(0xDA)
ST7789_RDID2 = const(0xDB)
ST7789_RDID3 = const(0xDC)
ST7789_RDID4 = const(0xDD)

COLOR_MODE_65K = const(0x50)
COLOR_MODE_262K = const(0x60)
COLOR_MODE_12BIT = const(0x03)
COLOR_MODE_16BIT = const(0x05)
COLOR_MODE_18BIT = const(0x06)
COLOR_MODE_16M = const(0x07)

# color order
RGB = 0x00
BGR = 0x08

# Color definitions
BLACK = const(0x0000)
BLUE = const(0x001F)
RED = const(0xF800)
GREEN = const(0x07E0)
CYAN = const(0x07FF)
MAGENTA = const(0xF81F)
YELLOW = const(0xFFE0)
WHITE = const(0xFFFF)

_ENCODE_PIXEL = ">H"
_ENCODE_POS = ">HH"
_DECODE_PIXEL = ">BBB"

_BUFFER_SIZE = const(256)

_BIT7 = const(0x80)
_BIT6 = const(0x40)
_BIT5 = const(0x20)
_BIT4 = const(0x10)
_BIT3 = const(0x08)
_BIT2 = const(0x04)
_BIT1 = const(0x02)
_BIT0 = const(0x01)
_BIT = [_BIT0, _BIT1, _BIT2, _BIT3, _BIT4, _BIT5, _BIT6, _BIT7]
# Rotation tables (width, height, xstart, ystart)[rotation % 4]

WIDTH_320 = [(240, 320, 0, 0), (320, 240, 0, 0), (240, 320, 0, 0), (320, 240, 0, 0)]

WIDTH_240 = [(240, 240, 0, 0), (240, 240, 0, 0), (240, 240, 0, 80), (240, 240, 80, 0)]

WIDTH_135 = [(135, 240, 52, 40), (240, 135, 40, 53), (135, 240, 53, 40), (240, 135, 40, 52)]

# MADCTL ROTATIONS[rotation % 4]
# ROTATIONS = [0x00, 0x60, 0xc0, 0xa0]
ROTATIONS = [0x40, 0xe0, 0x80, 0x20]  # 修正镜像显示问题


def color565(red, green=0, blue=0):
    """
    将红、绿、蓝分量值（0-255）转换为16位565编码。

    参数:
    red (int 或 tuple/list): 红分量值或包含 (red, green, blue) 值的元组/列表。
    green (int): 绿分量值。默认为0。
    blue (int): 蓝分量值。默认为0。

    返回:
    int: 16位565编码的颜色值。
    """
    try:
        # 如果 red 是一个元组或列表，解包前三个元素到 red, green, 和 blue
        if isinstance(red, (tuple, list)):
            if len(red) < 3 or not all(isinstance(x, int) for x in red[:3]):
                raise ValueError("输入的元组或列表必须至少包含三个整数")
            red, green, blue = red[:3]

        # 验证输入值是否在 0-255 范围内
        if not (0 <= red <= 255 and 0 <= green <= 255 and 0 <= blue <= 255):
            raise ValueError("RGB 分量值必须在 0-255 范围内")

        # 将 RGB 值转换为 565 编码
        return (red & 0xF8) << 8 | (green & 0xFC) << 3 | blue >> 3

    except ValueError as e:
        print(f"错误: {e}")
        return None


def _encode_pos(x, y):
    """将位置编码为字节。

    该函数接收两个坐标 x 和 y，使用 struct 模块将它们编码为字节格式。
    编码的目的是将位置信息转换为易于存储或传输的格式。

    参数:
    x (int/float): 位置的 x 坐标。
    y (int/float): 位置的 y 坐标。

    返回值:
    bytes: 编码后的位置的字节表示。
    """
    return struct.pack(_ENCODE_POS, x, y)


def _encode_pixel(color):
    """
    Encode a pixel color into bytes.

    This function takes a color value and encodes it into a byte format according to a predefined structure.
    It is primarily used for converting color information into a format that can be stored or transmitted.

    Parameters:
    - color: The color value to be encoded, usually an integer or a color represented in a specific format.

    Returns:
    - bytes: The encoded color information in byte format.
    """
    return struct.pack(_ENCODE_PIXEL, color)


class ST7789():
    """
    ST7789驱动类

    参数:
        spi (spi): SPI对象 **必需**
        width (int): 显示宽度 **必需**
        height (int): 显示高度 **必需**
        reset (pin): 复位引脚
        dc (pin): 数据/命令引脚 **必需**
        cs (pin): 片选引脚
        backlight (pin): 背光引脚
        rotation (int): 显示旋转方向
            - 0-竖屏
            - 1-横屏
            - 2-倒置竖屏
            - 3-倒置横屏
    """

    def __init__(self, spi=None, width=240, height=320, reset=None, dc=None, cs=None, backlight=None, rotation=0,
                 color_order=BGR):
        """
        初始化显示屏。

        :param spi: 用于通信的SPI接口。
        :param width: 显示屏宽度。
        :param height: 显示屏高度。
        :param reset: 复位引脚。
        :param dc: 数据/命令引脚。
        :param cs: 片选引脚。
        :param backlight: 背光控制引脚。
        :param rotation: 屏幕旋转角度。
        :param color_order: 颜色顺序，默认为BGR。
        :raises ValueError: 如果显示屏尺寸不受支持或缺少必要的引脚。
        """
        # 检查是否支持的显示屏尺寸
        if height != 240 or width not in [320, 240, 135]:
            raise ValueError("不支持的显示屏。支持的尺寸为：320x240、240x240 和 135x240。")

        # 确保提供了dc引脚
        if dc is None:
            raise ValueError("必须提供dc引脚。")

        # 初始化显示屏尺寸
        self._display_width = self.width = width
        self._display_height = self.height = height
        self.xstart = 0
        self.ystart = 0
        self.spi = spi
        self.reset = reset
        self.dc = dc
        self.cs = cs
        self.backlight = backlight
        self._rotation = rotation % 4
        self.color_order = color_order

        # 初始化引脚
        # self.hard_reset()
        # self.soft_reset()
        if self.cs is not None:
            self.cs.init(self.cs.OUT, value=1)

        if self.dc is not None:
            self.dc.init(self.dc.OUT, value=0)

        if self.reset is not None:
            self.reset.init(self.reset.OUT, value=1)

        # 配置显示屏设置
        self.sleep_mode(False)

        self._set_color_mode(COLOR_MODE_65K | COLOR_MODE_16BIT)
        time.sleep_ms(50)

        self.inversion_mode(False)
        time.sleep_ms(10)

        self.rotation(self._rotation)
        time.sleep_ms(50)

        self._write(ST7789_NORON)
        time.sleep_ms(10)
        if backlight is not None:
            # backlight.value(1)
            self.backlight.init(self.backlight.OUT, value=1)

        self._write(ST7789_DISPON)
        time.sleep_ms(500)
        # self.fill(0)
        self.fill(BLACK)

        # 初始化图片显示器
        self.image_displayer = ImageDisplayer(self)
        self.text_displayer = TextDisplayer(self)

    def _write(self, command=None, data=None):
        """SPI write to the device: commands and data."""
        if self.cs:
            self.cs.off()

        if command is not None:
            self.dc.off()
            self.spi.write(bytes([command]))
        if data is not None:
            self.dc.on()
            self.spi.write(data)
            if self.cs:
                self.cs.on()

    def hard_reset(self):
        """
        Hard reset display.
        """
        if self.cs:
            self.cs.off()
        if self.reset:
            self.reset.on()
        time.sleep_ms(50)
        if self.reset:
            self.reset.off()
        time.sleep_ms(50)
        if self.reset:
            self.reset.on()
        time.sleep_ms(150)
        if self.cs:
            self.cs.on()

    def soft_reset(self):
        """
        Soft reset display.
        """
        self._write(ST7789_SWRESET)
        time.sleep_ms(150)

    def sleep_mode(self, value):
        """
        Enable or disable display sleep mode.

        Args:
            value (bool): if True enable sleep mode. if False disable sleep
            mode
        """
        if value:
            self._write(ST7789_SLPIN)
        else:
            self._write(ST7789_SLPOUT)

    def inversion_mode(self, value):
        """
        启用或禁用显示反转模式。

        参数:
            value (bool): 如果为True，则启用反转模式；如果为False，则禁用反转模式。
        """
        if value:
            self._write(ST7789_INVON)
        else:
            self._write(ST7789_INVOFF)

    def _set_color_mode(self, mode):
        """
        Set display color mode.

        Args:
            mode (int): color mode
                COLOR_MODE_65K, COLOR_MODE_262K, COLOR_MODE_12BIT,
                COLOR_MODE_16BIT, COLOR_MODE_18BIT, COLOR_MODE_16M
        """
        self._write(ST7789_COLMOD, bytes([mode & 0x77]))

    def rotation(self, rotation):
        """
        设置显示旋转方向。

        参数:
            rotation (int):
                - 0-竖屏
                - 1-横屏
                - 2-倒置竖屏
                - 3-倒置横屏
        """

        rotation %= 4
        self._rotation = rotation
        madctl = ROTATIONS[rotation]

        if self._display_width == 320:
            table = WIDTH_320
        elif self._display_width == 240:
            table = WIDTH_240
        elif self._display_width == 135:
            table = WIDTH_135
        else:
            raise ValueError("Unsupported display. 320x240, 240x240 and 135x240 are supported.")

        self.width, self.height, self.xstart, self.ystart = table[rotation]
        # self._write(ST7789_MADCTL, bytes([madctl]))
        # 增加颜色顺序支持
        if self.color_order == BGR:
            madctl |= ST7789_MADCTL_BGR
        else:
            madctl &= ~ST7789_MADCTL_BGR

        self._write(ST7789_MADCTL, bytes([madctl]))

    def _set_columns(self, start, end):
        """
        Send CASET (column address set) command to display.

        Args:
            start (int): column start address
            end (int): column end address
        """
        if start <= end <= self.width:
            self._write(ST7789_CASET, _encode_pos(start + self.xstart, end + self.xstart))

    def _set_rows(self, start, end):
        """
        Send RASET (row address set) command to display.

        Args:
            start (int): row start address
            end (int): row end address
       """
        if start <= end <= self.height:
            self._write(ST7789_RASET, _encode_pos(start + self.ystart, end + self.ystart))

    def _set_window(self, x0, y0, x1, y1):
        """
        Set window to column and row address.

        Args:
            x0 (int): column start address
            y0 (int): row start address
            x1 (int): column end address
            y1 (int): row end address
        """
        self._set_columns(x0, x1)
        self._set_rows(y0, y1)
        self._write(ST7789_RAMWR)

    def vline(self, x, y, length, color):
        """
        Draw vertical line at the given location and color.

        Args:
            x (int): x coordinate
            Y (int): y coordinate
            length (int): length of line
            color (int): 565 encoded color
        """
        self.fill_rect(x, y, 1, length, color)

    def hline(self, x, y, length, color):
        """
        Draw horizontal line at the given location and color.

        Args:
            x (int): x coordinate
            Y (int): y coordinate
            length (int): length of line
            color (int): 565 encoded color
        """
        self.fill_rect(x, y, length, 1, color)

    def pixel(self, x, y, color):
        """
        Draw a pixel at the given location and color.

        Args:
            x (int): x coordinate
            Y (int): y coordinate
            color (int): 565 encoded color
        """
        self._set_window(x, y, x, y)
        self._write(None, _encode_pixel(color))

    def blit_buffer(self, buffer, x, y, width, height):
        """
        Copy buffer to display at the given location.

        Args:
            buffer (bytes): Data to copy to display
            x (int): Top left corner x coordinate
            Y (int): Top left corner y coordinate
            width (int): Width
            height (int): Height
        """
        self._set_window(x, y, x + width - 1, y + height - 1)
        self._write(None, buffer)

    def rect(self, x, y, w, h, color):
        """
        Draw a rectangle at the given location, size and color.

        Args:
            x (int): Top left corner x coordinate
            y (int): Top left corner y coordinate
            width (int): Width in pixels
            height (int): Height in pixels
            color (int): 565 encoded color
        """
        self.hline(x, y, w, color)
        self.vline(x, y, h, color)
        self.vline(x + w - 1, y, h, color)
        self.hline(x, y + h - 1, w, color)

    def fill_rect(self, x, y, width, height, color):
        """
        Draw a rectangle at the given location, size and filled with color.

        Args:
            x (int): Top left corner x coordinate
            y (int): Top left corner y coordinate
            width (int): Width in pixels
            height (int): Height in pixels
            color (int): 565 encoded color
        """
        self._set_window(x, y, x + width - 1, y + height - 1)
        chunks, rest = divmod(width * height, _BUFFER_SIZE)
        pixel = _encode_pixel(color)
        self.dc.on()
        if chunks:
            data = pixel * _BUFFER_SIZE
            for _ in range(chunks):
                self._write(None, data)
        if rest:
            self._write(None, pixel * rest)

    def fill(self, color):
        """
        Fill the entire FrameBuffer with the specified color.

        Args:
            color (int): 565 encoded color
        """
        self.fill_rect(0, 0, self.width, self.height, color)

    def line(self, x0, y0, x1, y1, color):
        """
        Draw a single pixel wide line starting at x0, y0 and ending at x1, y1.

        Args:
            x0 (int): Start point x coordinate
            y0 (int): Start point y coordinate
            x1 (int): End point x coordinate
            y1 (int): End point y coordinate
            color (int): 565 encoded color
        """
        steep = abs(y1 - y0) > abs(x1 - x0)
        if steep:
            x0, y0 = y0, x0
            x1, y1 = y1, x1
        if x0 > x1:
            x0, x1 = x1, x0
            y0, y1 = y1, y0
        dx = x1 - x0
        dy = abs(y1 - y0)
        err = dx // 2
        ystep = 1 if y0 < y1 else -1
        while x0 <= x1:
            if steep:
                self.pixel(y0, x0, color)
            else:
                self.pixel(x0, y0, color)
            err -= dy
            if err < 0:
                y0 += ystep
                err += dx
            x0 += 1

    def vscrdef(self, tfa, vsa, bfa):
        """
        设置垂直滚动定义。

        对于一个135x240的显示屏，这些值应为40, 240, 40。
        屏幕上方有40行未显示，接着是240行显示内容，最后再跟40行未显示。
        你可以写入这些未显示区域，并通过更改TFA、VSA和BFA值将它们滚动到视图中。

        参数:
            tfa (int): 顶部固定区域
            vsa (int): 垂直滚动区域
            bfa (int): 底部固定区域
        """
        struct.pack(">HHH", tfa, vsa, bfa)
        self._write(ST7789_VSCRDEF, struct.pack(">HHH", tfa, vsa, bfa))

    def vscsad(self, vssa):
        """
        Set Vertical Scroll Start Address of RAM.

        Defines which line in the Frame Memory will be written as the first
        line after the last line of the Top Fixed Area on the display

        Example:

            for line in range(40, 280, 1):
                tft.vscsad(line)
                utime.sleep(0.01)

        Args:
            vssa (int): Vertical Scrolling Start Address

        """
        self._write(ST7789_VSCSAD, struct.pack(">H", vssa))


    def text_gb(self, font, size, text, x0, y0, color=WHITE, background=BLACK):
        """
        显示中文
        font (class): 字体
        size (int): 字体大小
        text (str): 要显示的中文文本（不能含有半角英文符号）
        x0 (int): column to start drawing at
        y0 (int): row to start drawing at
        color (int): 565 encoded color to use for background
        background (int): 565 encoded color to use for background
        """
        # 使用大端序 '>H' 确保字节序一致
        color_bytes = struct.pack('>H', color)
        background_bytes = struct.pack('>H', background)

        buffer = bytearray(font.WIDTH * font.HEIGHT * 2)  # 预分配整个字符的缓冲区

        for char in text:
            if (x0 + font.WIDTH <= self.width and y0 + font.HEIGHT <= self.height):
                buffer_index = 0

                for line in range(2):  # 分两次显示，先显示上半边后显示下半边
                    idx = line * (font.SIZE // 2)
                    for x in range(font.SIZE // 2):
                        byte_value = font.FONT[char][idx + x]
                        for i in range(8):
                            if byte_value & _BIT[7 - i]:
                                buffer[buffer_index:buffer_index + 2] = color_bytes
                            else:
                                buffer[buffer_index:buffer_index + 2] = background_bytes
                            buffer_index += 2

                # 使用 blit_buffer 一次性传输整个字符的数据
                self.blit_buffer(buffer, x0, y0, font.WIDTH, font.HEIGHT)
                x0 += font.WIDTH  # 显示下一个字的时候x坐标增加字体宽度

    def text(self, size=16, text=None, x0=0, y0=0, color=WHITE, background=BLACK):
        """
        Draw text on display in specified font and colors. 8 and 16 bit wide
        fonts are supported.

        Args:
            size : 中文支持16,24,32,48；英文默认使用16号字体，支持8、16种字号.
            text (str): text to write
            x0 (int): column to start drawing at
            y0 (int): row to start drawing at
            color (int): 565 encoded color to use for characters
            background (int): 565 encoded color to use for background
        """
        if not size in [8, 16, 24, 32, 48]:
            print(f"不支持{size}号大小的字体。")
            size = 16

        current_x = x0
        i = 0
        while i < len(text):
            char = text[i]

            # 英文字母只有8号和16号字体，默认使用16号字体，不带粗体，如果需要粗体，
            # 请修改代码导入的字库，从romfonts文件夹中复制字库文件

            if len(char.encode('utf-8')) == 1 and size <= 32:  # ASCII
                if size == 8:
                    self.text_displayer.text8(font8, char, current_x, y0, color, background)
                    current_x += 8
                else:
                    # 英文只支持2种大小的字体，默认使用16号字体
                    self.text_displayer.text16(font16, char, current_x, y0, color, background)
                    current_x += 16

            # 汉字只有16,24,32号字体，包含完整的汉字字库
            # 48号字体为自定义的字体，随机附带的字库定义了时钟显示需要的几个数字和符号
            else:  # UNICODE
                if size == 16:
                    font_gb = GB16.str(char)  # 使用字体文件
                elif size == 24:
                    font_gb = GB24.str(char)  # 使用字体文件
                elif size == 32:
                    # font_gb = GB32
                    font_gb = GB32.str(char)  # 使用字体文件
                elif size == 48:
                    font_gb = GB48
                self.text_gb(font_gb, size, char, current_x, y0, color, background)
                current_x += font_gb.WIDTH  # 假设font.WIDTH是全角字符的宽度
            i += 1

    def display_bmp(self, file_path, x, y):
        """
        在 TFT 显示屏上显示 BMP 图像。

        参数:
            file_path (str): BMP 文件的路径。
            x (int): 图像显示的起始 x 坐标。
            y (int): 图像显示的起始 y 坐标。
        """
        self.image_displayer.display_bmp(file_path, x, y)

    def bitmap(self, bitmap, x, y, index=0):
        """
        在指定的列和行绘制位图。

        参数:
            bitmap (bitmap_module): 包含要绘制的位图的模块
            x (int): 开始绘制的列
            y (int): 开始绘制的行
            index (int): 可选参数，从多个位图模块中选择要绘制的位图索引

        """
        bitmap_size = bitmap.HEIGHT * bitmap.WIDTH
        buffer_len = bitmap_size * 2
        buffer = bytearray(buffer_len)
        bs_bit = bitmap.BPP * bitmap_size * index if index > 0 else 0

        for i in range(0, buffer_len, 2):
            color_index = 0
            for _ in range(bitmap.BPP):
                color_index <<= 1
                color_index |= (bitmap.BITMAP[bs_bit // 8] & 1 << (7 - (bs_bit % 8))) > 0
                bs_bit += 1

            color = bitmap.PALETTE[color_index]
            buffer[i] = color & 0xff00 >> 8
            buffer[i + 1] = color_index & 0xff

        to_col = x + bitmap.WIDTH - 1
        to_row = y + bitmap.HEIGHT - 1
        if self.width > to_col and self.height > to_row:
            self._set_window(x, y, to_col, to_row)
            self._write(None, buffer)

    # @micropython.native
    def write(self, font, string, x, y, fg=WHITE, bg=BLACK):
        """
        使用转换后的 TrueType 字体在显示屏上从指定的列和行开始写入字符串。

        参数:
            font (font): 包含转换后的 TrueType 字体的模块
            s (string): 要写入的字符串
            x (int): 开始写入的列
            y (int): 开始写入的行
            fg (int): 前景色，默认为白色
            bg (int): 背景色，默认为黑色
        """
        buffer_len = font.HEIGHT * font.MAX_WIDTH * 2
        buffer = bytearray(buffer_len)
        fg_hi = (fg & 0xff00) >> 8
        fg_lo = fg & 0xff

        bg_hi = (bg & 0xff00) >> 8
        bg_lo = bg & 0xff

        for character in string:
            try:
                char_index = font.MAP.index(character)
                offset = char_index * font.OFFSET_WIDTH
                bs_bit = font.OFFSETS[offset]
                if font.OFFSET_WIDTH > 1:
                    bs_bit = (bs_bit << 8) + font.OFFSETS[offset + 1]

                if font.OFFSET_WIDTH > 2:
                    bs_bit = (bs_bit << 8) + font.OFFSETS[offset + 2]

                char_width = font.WIDTHS[char_index]
                buffer_needed = char_width * font.HEIGHT * 2

                for i in range(0, buffer_needed, 2):
                    if font.BITMAPS[bs_bit // 8] & 1 << (7 - (bs_bit % 8)) > 0:
                        buffer[i] = fg_hi
                        buffer[i + 1] = fg_lo
                    else:
                        buffer[i] = bg_hi
                        buffer[i + 1] = bg_lo

                    bs_bit += 1

                to_col = x + char_width - 1
                to_row = y + font.HEIGHT - 1
                if self.width > to_col and self.height > to_row:
                    self._set_window(x, y, to_col, to_row)
                    self._write(None, buffer[:buffer_needed])

                x += char_width

            except ValueError:
                pass

    def write_width(self, font, string):
        """
        返回使用指定字体写入字符串时的像素宽度。

        参数:
            font (font): 包含转换后的 TrueType 字体的模块
            string (string): 要测量的字符串
        """
        width = 0
        for character in string:
            try:
                char_index = font.MAP.index(character)
                width += font.WIDTHS[char_index]

            except ValueError:
                pass

        return width

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.spi.deinit()


class ImageDisplayer:
    def __init__(self, tft_display):
        self.tft_display = tft_display

    def read_bmp_header(self, file):
        """
        读取 BMP 文件头信息。

        参数:
            file (file): 打开的 BMP 文件对象。

        返回:
            tuple: 包含偏移量、宽度、高度和深度的元组。
        """
        if file.read(2) != b'BM':
            raise ValueError("不是 BMP 文件")
        file.read(8)  # 文件大小(4字节), 创建者字节(4字节)
        offset = int.from_bytes(file.read(4), 'little')
        file.read(4)  # DIB 头大小
        width = int.from_bytes(file.read(4), 'little')
        height = int.from_bytes(file.read(4), 'little')
        if int.from_bytes(file.read(2), 'little') != 1:  # 平面数必须为1
            raise ValueError("平面数必须为1")
        depth = int.from_bytes(file.read(2), 'little')
        if depth != 24 or int.from_bytes(file.read(4), 'little') != 0:  # 压缩方法必须为无压缩
            raise ValueError("不支持的 BMP 格式")
        return offset, width, height

    def display_bmp(self, file_path, x, y):
        """
        在 TFT 显示屏上显示 BMP 图像。

        参数:
            file_path (str): BMP 文件的路径。
            x (int): 图像显示的起始 x 坐标。
            y (int): 图像显示的起始 y 坐标。
        """
        with open(file_path, 'rb') as f:
            offset, width, height = self.read_bmp_header(f)
            rowsize = (width * 3 + 3) & ~3
            flip = height > 0
            if height < 0:
                height = -height
            w, h = width, height
            self.tft_display._set_window(x, y, x + w - 1, y + h - 1)

            buffer = bytearray(rowsize)
            for row in range(h):
                if flip:
                    pos = offset + (height - 1 - row) * rowsize
                else:
                    pos = offset + row * rowsize
                if f.tell() != pos:
                    f.seek(pos)
                f.readinto(buffer)
                pixels = bytearray(w * 2)  # 每个像素2字节
                for col in range(w):
                    bgr = buffer[col * 3:col * 3 + 3]
                    color = color565(bgr[2], bgr[1], bgr[0])
                    pixels[col * 2:(col * 2 + 2)] = struct.pack('>H', color)
                self.tft_display.blit_buffer(pixels, x, y + row, w, 1)




class TextDisplayer:
    def __init__(self, tft_display):
        self.tft_display = tft_display


    def text8(self, font, text, x0, y0, color=WHITE, background=BLACK):
        """
        Internal method to write characters with width of 8 and
        heights of 8 or 16.

        Args:
            font (module): font module to use
            text (str): text to write
            x0 (int): column to start drawing at
            y0 (int): row to start drawing at
            color (int): 565 encoded color to use for characters
            background (int): 565 encoded color to use for background
        """
        for char in text:
            ch = ord(char)
            if (font.FIRST <= ch < font.LAST and x0 + font.WIDTH <= self.tft_display.width and y0 + font.HEIGHT <= self.tft_display.height):

                if font.HEIGHT == 8:
                    passes = 1
                    size = 8
                    each = 0
                else:
                    passes = 2
                    size = 16
                    each = 8

                for line in range(passes):
                    idx = (ch - font.FIRST) * size + (each * line)
                    buffer = struct.pack('>64H', color if font.FONT[idx] & _BIT7 else background,
                        color if font.FONT[idx] & _BIT6 else background,
                        color if font.FONT[idx] & _BIT5 else background,
                        color if font.FONT[idx] & _BIT4 else background,
                        color if font.FONT[idx] & _BIT3 else background,
                        color if font.FONT[idx] & _BIT2 else background,
                        color if font.FONT[idx] & _BIT1 else background,
                        color if font.FONT[idx] & _BIT0 else background,
                        color if font.FONT[idx + 1] & _BIT7 else background,
                        color if font.FONT[idx + 1] & _BIT6 else background,
                        color if font.FONT[idx + 1] & _BIT5 else background,
                        color if font.FONT[idx + 1] & _BIT4 else background,
                        color if font.FONT[idx + 1] & _BIT3 else background,
                        color if font.FONT[idx + 1] & _BIT2 else background,
                        color if font.FONT[idx + 1] & _BIT1 else background,
                        color if font.FONT[idx + 1] & _BIT0 else background,
                        color if font.FONT[idx + 2] & _BIT7 else background,
                        color if font.FONT[idx + 2] & _BIT6 else background,
                        color if font.FONT[idx + 2] & _BIT5 else background,
                        color if font.FONT[idx + 2] & _BIT4 else background,
                        color if font.FONT[idx + 2] & _BIT3 else background,
                        color if font.FONT[idx + 2] & _BIT2 else background,
                        color if font.FONT[idx + 2] & _BIT1 else background,
                        color if font.FONT[idx + 2] & _BIT0 else background,
                        color if font.FONT[idx + 3] & _BIT7 else background,
                        color if font.FONT[idx + 3] & _BIT6 else background,
                        color if font.FONT[idx + 3] & _BIT5 else background,
                        color if font.FONT[idx + 3] & _BIT4 else background,
                        color if font.FONT[idx + 3] & _BIT3 else background,
                        color if font.FONT[idx + 3] & _BIT2 else background,
                        color if font.FONT[idx + 3] & _BIT1 else background,
                        color if font.FONT[idx + 3] & _BIT0 else background,
                        color if font.FONT[idx + 4] & _BIT7 else background,
                        color if font.FONT[idx + 4] & _BIT6 else background,
                        color if font.FONT[idx + 4] & _BIT5 else background,
                        color if font.FONT[idx + 4] & _BIT4 else background,
                        color if font.FONT[idx + 4] & _BIT3 else background,
                        color if font.FONT[idx + 4] & _BIT2 else background,
                        color if font.FONT[idx + 4] & _BIT1 else background,
                        color if font.FONT[idx + 4] & _BIT0 else background,
                        color if font.FONT[idx + 5] & _BIT7 else background,
                        color if font.FONT[idx + 5] & _BIT6 else background,
                        color if font.FONT[idx + 5] & _BIT5 else background,
                        color if font.FONT[idx + 5] & _BIT4 else background,
                        color if font.FONT[idx + 5] & _BIT3 else background,
                        color if font.FONT[idx + 5] & _BIT2 else background,
                        color if font.FONT[idx + 5] & _BIT1 else background,
                        color if font.FONT[idx + 5] & _BIT0 else background,
                        color if font.FONT[idx + 6] & _BIT7 else background,
                        color if font.FONT[idx + 6] & _BIT6 else background,
                        color if font.FONT[idx + 6] & _BIT5 else background,
                        color if font.FONT[idx + 6] & _BIT4 else background,
                        color if font.FONT[idx + 6] & _BIT3 else background,
                        color if font.FONT[idx + 6] & _BIT2 else background,
                        color if font.FONT[idx + 6] & _BIT1 else background,
                        color if font.FONT[idx + 6] & _BIT0 else background,
                        color if font.FONT[idx + 7] & _BIT7 else background,
                        color if font.FONT[idx + 7] & _BIT6 else background,
                        color if font.FONT[idx + 7] & _BIT5 else background,
                        color if font.FONT[idx + 7] & _BIT4 else background,
                        color if font.FONT[idx + 7] & _BIT3 else background,
                        color if font.FONT[idx + 7] & _BIT2 else background,
                        color if font.FONT[idx + 7] & _BIT1 else background,
                        color if font.FONT[idx + 7] & _BIT0 else background)
                    self.tft_display.blit_buffer(buffer, x0, y0 + 8 * line, 8, 8)

                x0 += 8


    def text16(self, font, text, x0, y0, color=WHITE, background=BLACK):
        """
        Internal method to draw characters with width of 16 and heights of 16
        or 32.

        Args:
            font (module): font module to use
            text (str): text to write
            x0 (int): column to start drawing at
            y0 (int): row to start drawing at
            color (int): 565 encoded color to use for characters
            background (int): 565 encoded color to use for background
        """
        for char in text:
            ch = ord(char)
            if (font.FIRST <= ch < font.LAST and x0 + font.WIDTH <= self.tft_display.width and y0 + font.HEIGHT <= self.tft_display.height):

                each = 16
                if font.HEIGHT == 16:
                    passes = 2
                    size = 32
                else:
                    passes = 4
                    size = 64

                for line in range(passes):
                    idx = (ch - font.FIRST) * size + (each * line)
                    buffer = struct.pack('>128H', color if font.FONT[idx] & _BIT7 else background,
                        color if font.FONT[idx] & _BIT6 else background,
                        color if font.FONT[idx] & _BIT5 else background,
                        color if font.FONT[idx] & _BIT4 else background,
                        color if font.FONT[idx] & _BIT3 else background,
                        color if font.FONT[idx] & _BIT2 else background,
                        color if font.FONT[idx] & _BIT1 else background,
                        color if font.FONT[idx] & _BIT0 else background,
                        color if font.FONT[idx + 1] & _BIT7 else background,
                        color if font.FONT[idx + 1] & _BIT6 else background,
                        color if font.FONT[idx + 1] & _BIT5 else background,
                        color if font.FONT[idx + 1] & _BIT4 else background,
                        color if font.FONT[idx + 1] & _BIT3 else background,
                        color if font.FONT[idx + 1] & _BIT2 else background,
                        color if font.FONT[idx + 1] & _BIT1 else background,
                        color if font.FONT[idx + 1] & _BIT0 else background,
                        color if font.FONT[idx + 2] & _BIT7 else background,
                        color if font.FONT[idx + 2] & _BIT6 else background,
                        color if font.FONT[idx + 2] & _BIT5 else background,
                        color if font.FONT[idx + 2] & _BIT4 else background,
                        color if font.FONT[idx + 2] & _BIT3 else background,
                        color if font.FONT[idx + 2] & _BIT2 else background,
                        color if font.FONT[idx + 2] & _BIT1 else background,
                        color if font.FONT[idx + 2] & _BIT0 else background,
                        color if font.FONT[idx + 3] & _BIT7 else background,
                        color if font.FONT[idx + 3] & _BIT6 else background,
                        color if font.FONT[idx + 3] & _BIT5 else background,
                        color if font.FONT[idx + 3] & _BIT4 else background,
                        color if font.FONT[idx + 3] & _BIT3 else background,
                        color if font.FONT[idx + 3] & _BIT2 else background,
                        color if font.FONT[idx + 3] & _BIT1 else background,
                        color if font.FONT[idx + 3] & _BIT0 else background,
                        color if font.FONT[idx + 4] & _BIT7 else background,
                        color if font.FONT[idx + 4] & _BIT6 else background,
                        color if font.FONT[idx + 4] & _BIT5 else background,
                        color if font.FONT[idx + 4] & _BIT4 else background,
                        color if font.FONT[idx + 4] & _BIT3 else background,
                        color if font.FONT[idx + 4] & _BIT2 else background,
                        color if font.FONT[idx + 4] & _BIT1 else background,
                        color if font.FONT[idx + 4] & _BIT0 else background,
                        color if font.FONT[idx + 5] & _BIT7 else background,
                        color if font.FONT[idx + 5] & _BIT6 else background,
                        color if font.FONT[idx + 5] & _BIT5 else background,
                        color if font.FONT[idx + 5] & _BIT4 else background,
                        color if font.FONT[idx + 5] & _BIT3 else background,
                        color if font.FONT[idx + 5] & _BIT2 else background,
                        color if font.FONT[idx + 5] & _BIT1 else background,
                        color if font.FONT[idx + 5] & _BIT0 else background,
                        color if font.FONT[idx + 6] & _BIT7 else background,
                        color if font.FONT[idx + 6] & _BIT6 else background,
                        color if font.FONT[idx + 6] & _BIT5 else background,
                        color if font.FONT[idx + 6] & _BIT4 else background,
                        color if font.FONT[idx + 6] & _BIT3 else background,
                        color if font.FONT[idx + 6] & _BIT2 else background,
                        color if font.FONT[idx + 6] & _BIT1 else background,
                        color if font.FONT[idx + 6] & _BIT0 else background,
                        color if font.FONT[idx + 7] & _BIT7 else background,
                        color if font.FONT[idx + 7] & _BIT6 else background,
                        color if font.FONT[idx + 7] & _BIT5 else background,
                        color if font.FONT[idx + 7] & _BIT4 else background,
                        color if font.FONT[idx + 7] & _BIT3 else background,
                        color if font.FONT[idx + 7] & _BIT2 else background,
                        color if font.FONT[idx + 7] & _BIT1 else background,
                        color if font.FONT[idx + 7] & _BIT0 else background,
                        color if font.FONT[idx + 8] & _BIT7 else background,
                        color if font.FONT[idx + 8] & _BIT6 else background,
                        color if font.FONT[idx + 8] & _BIT5 else background,
                        color if font.FONT[idx + 8] & _BIT4 else background,
                        color if font.FONT[idx + 8] & _BIT3 else background,
                        color if font.FONT[idx + 8] & _BIT2 else background,
                        color if font.FONT[idx + 8] & _BIT1 else background,
                        color if font.FONT[idx + 8] & _BIT0 else background,
                        color if font.FONT[idx + 9] & _BIT7 else background,
                        color if font.FONT[idx + 9] & _BIT6 else background,
                        color if font.FONT[idx + 9] & _BIT5 else background,
                        color if font.FONT[idx + 9] & _BIT4 else background,
                        color if font.FONT[idx + 9] & _BIT3 else background,
                        color if font.FONT[idx + 9] & _BIT2 else background,
                        color if font.FONT[idx + 9] & _BIT1 else background,
                        color if font.FONT[idx + 9] & _BIT0 else background,
                        color if font.FONT[idx + 10] & _BIT7 else background,
                        color if font.FONT[idx + 10] & _BIT6 else background,
                        color if font.FONT[idx + 10] & _BIT5 else background,
                        color if font.FONT[idx + 10] & _BIT4 else background,
                        color if font.FONT[idx + 10] & _BIT3 else background,
                        color if font.FONT[idx + 10] & _BIT2 else background,
                        color if font.FONT[idx + 10] & _BIT1 else background,
                        color if font.FONT[idx + 10] & _BIT0 else background,
                        color if font.FONT[idx + 11] & _BIT7 else background,
                        color if font.FONT[idx + 11] & _BIT6 else background,
                        color if font.FONT[idx + 11] & _BIT5 else background,
                        color if font.FONT[idx + 11] & _BIT4 else background,
                        color if font.FONT[idx + 11] & _BIT3 else background,
                        color if font.FONT[idx + 11] & _BIT2 else background,
                        color if font.FONT[idx + 11] & _BIT1 else background,
                        color if font.FONT[idx + 11] & _BIT0 else background,
                        color if font.FONT[idx + 12] & _BIT7 else background,
                        color if font.FONT[idx + 12] & _BIT6 else background,
                        color if font.FONT[idx + 12] & _BIT5 else background,
                        color if font.FONT[idx + 12] & _BIT4 else background,
                        color if font.FONT[idx + 12] & _BIT3 else background,
                        color if font.FONT[idx + 12] & _BIT2 else background,
                        color if font.FONT[idx + 12] & _BIT1 else background,
                        color if font.FONT[idx + 12] & _BIT0 else background,
                        color if font.FONT[idx + 13] & _BIT7 else background,
                        color if font.FONT[idx + 13] & _BIT6 else background,
                        color if font.FONT[idx + 13] & _BIT5 else background,
                        color if font.FONT[idx + 13] & _BIT4 else background,
                        color if font.FONT[idx + 13] & _BIT3 else background,
                        color if font.FONT[idx + 13] & _BIT2 else background,
                        color if font.FONT[idx + 13] & _BIT1 else background,
                        color if font.FONT[idx + 13] & _BIT0 else background,
                        color if font.FONT[idx + 14] & _BIT7 else background,
                        color if font.FONT[idx + 14] & _BIT6 else background,
                        color if font.FONT[idx + 14] & _BIT5 else background,
                        color if font.FONT[idx + 14] & _BIT4 else background,
                        color if font.FONT[idx + 14] & _BIT3 else background,
                        color if font.FONT[idx + 14] & _BIT2 else background,
                        color if font.FONT[idx + 14] & _BIT1 else background,
                        color if font.FONT[idx + 14] & _BIT0 else background,
                        color if font.FONT[idx + 15] & _BIT7 else background,
                        color if font.FONT[idx + 15] & _BIT6 else background,
                        color if font.FONT[idx + 15] & _BIT5 else background,
                        color if font.FONT[idx + 15] & _BIT4 else background,
                        color if font.FONT[idx + 15] & _BIT3 else background,
                        color if font.FONT[idx + 15] & _BIT2 else background,
                        color if font.FONT[idx + 15] & _BIT1 else background,
                        color if font.FONT[idx + 15] & _BIT0 else background)
                    self.tft_display.blit_buffer(buffer, x0, y0 + 8 * line, 16, 8)
            x0 += font.WIDTH